//index.js
//获取应用实例
const http = require("../../utils/util.js");
var Crypto = require('../../utils/cryptojs/cryptojs.js').Crypto;
const app = getApp();
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
var tempFilePath;
Page({
  data: {
    houBaoStyle:1,
    userInfo:[],
    shuoming1:'小伙伴们说对口令就能获得随即打赏',
    shuoming2:'好友听完你说的话就能领取赏金',
    shuoming3:'好友念出你的答案就能领取赏金',
    kouling:'', 
    Money:'',
    Number:'',
    answer:'',
    // 录音动画；
    isSpeaking: false,
    speakerUrl: '../image/speaker0.png',
    speakerUrlPrefix: '../image/speaker',
    speakerUrlSuffix: '.png',

    voiceResult:false,
  },
  //事件处理函数
  ChangeTab:function(e){
    var that = this; 
    var currentTab = e.currentTarget.dataset.id;
    console.log(currentTab)
    that.setData({
      houBaoStyle: currentTab,
    })
  },
  onLoad: function () {
    var that = this;
    wx.getUserInfo({
      success:function(user){
        console.log(user)
        that.setData({
          userInfo:user.userInfo,
        })
      }
    })
    // 判断是否需要调用登陆；
    wx.getStorage({
      key: 'token',
      success: function (res) {
        console.log("获取token APP")
        console.log(res.data);
        var token = res.data;
        if (token == '' || token == undefined) {
          app.login();
        }

      },
      fail: function (res) {
        console.log("获取toekn 失败")
        console.log(res)
        app.login();
      }
    })
  },
// 口令红白生成

  // 测试语音播放结果；
  play: function () {
    console.log("zhixi")
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })

  },
  // 获取语音
  startVoice: function () {
    var that = this;
    app.getVoice();
  },
  endstartVoice: function () {
    var that = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      console.log('停止录音', res.tempFilePath)
      that.uploadVoice(res.tempFilePath);
    })
  },
  // 上传语音：
  uploadVoice: function (tempFilePath) {
    var that = this;
    console.log("程序进入上传语音");
    // var tempFilePath = that.tempFilePath
 
    console.log(tempFilePath);
    wx.getStorage({
      key: 'token',
      success: function (res) {
        const token = res.data;
        const url = app.globalData.localApi + "/redpack/receiveVoice";
        console.log("上传语音url：" + url);
        console.log("上传语音filePath：" + tempFilePath);
        var userInfo = app.globalData.userInfo;
        console.log(userInfo);
        // wx.request({
        //   url: url,
        //   method:"POST",
        //   data:{
        //     userInfo:userInfo,
        //     token:token,
        //   },
        //   success:function(res){
        //     console.log(res);
        //   }
        // })
        wx.uploadFile({
          url: url,
          filePath: tempFilePath,
          name: "file",
          formData: {
            "userInfo":userInfo,
            "token": token,
          },
          header: { "Content-Type": "multipart/form-data" },
          success: function (res) {
            console.log("请求成功")
            console.log(res)
            that.setData({
              voiceResult: true,
            })
          },
          fail: function (res) {
            console.log(res)
            console.log("上传失败")
            app.showInfo("网络开小差了,语音没有上传成功")
            that.setData({
              voiceResult: false,
            })
          }
        })
      },
    })
  },
  // 跳转链接
  tomyRecord:function(){
    var that = this;
    wx.navigateTo({
      url: './mRecord/myRecord',
    })

  },
  toShare:function(){
    var that = this;
    console.log(that.data.houBaoStyle)
    // 正式：
    var HotStyle = that.data.houBaoStyle.toString();
    switch (HotStyle){
      case "1":
        that.iskouling();
        break;
      case "2":
        that.isqingting();
        break;
      case "3":
        that.isjuben();
        break;
    }
  },
  iskouling:function(){
    var that = this;
    // that.perpay();
    console.log("执行isKouling")
    if (that.data.kouling == '') {
      app.showInfo("请设置口令");
    } else if (that.data.Money == '') {
      app.showInfo("请输入赏金");
    } else if (that.data.Number == '') {
      app.showInfo("请设置红包个数");
    } else {
      that.perpay();
    }
  },
  isqingting:function(){
    var that = this;
    console.log("执行倾听")
    // that.perpay();
    if (!that.data.voiceResult){
      app.showInfo("请重新上传语音")
    } else if (that.data.Money == '') {
      app.showInfo("请输入赏金");
    } else if (that.data.Number == '') {
      app.showInfo("请设置红包个数");
    } else {
      that.perpay();
    }

  },
  isjuben:function(){
    var that = this;
    console.log("执行剧本")
    // that.perpay();
    if (!that.data.voiceResult) {
      app.showInfo("请重新上传语音")
    } else if (that.data.answer==''){
      app.showInfo("请输入问题的答案")
    }else if (that.data.Money == '') {
      app.showInfo("请输入赏金");
    } else if (that.data.Number == '') {
      app.showInfo("请设置红包个数");
    } else {
      that.perpay();
    }
  },
  // perpay:function(){
  //   var that = this;
  //   wx.navigateTo({
  //     url: './Share/ShareHotMoney?houBaoStyle=' + that.data.houBaoStyle
  //     + "&Money=" + that.data.Money
  //     + "&Number=" + that.data.Number
  //     + "&kouling=" + that.data.kouling,
  //   })
  // },
  perpay:function(){
    console.log("执行perPay")
    var that = this;
    var url = app.globalData.localApi +"/redpack/prepay";
    wx.getStorage({
      key: 'token',
      success: function(res) {
        console.log(res.data);
        var token = res.data;
        var timestamp = app.timestamp()
        console.log(that.data.houbaoStyle)
        wx.request({
          url: url,
          method: "POST",
          data: {
            timestamp:timestamp,
            token: token,
            sign: Crypto.MD5(app.sign(url,token,timestamp)),
            packText:that.data.kouling,
            packMoney:that.data.Money*100,
            packCount:parseInt(that.data.Number),
            packAnswer:that.data.answer,
            packType: that.data.houBaoStyle
          }, 
          success:function(res){
            console.log("prepay执行成功")
            console.log(res)
            that.setData({
              orderno:res.data.data.orderinfo.orderno
            })
            wx.navigateTo({
              url: './Share/share?houBaoStyle=' + that.data.houBaoStyle
              + "&Money=" + that.data.Money
              + "&Number=" + that.data.Number
              + "&kouling=" + that.data.kouling
              + "&orderno=" + that.data.orderno,
            })
            // d微信支付；
            // wx.requestPayment({
            //   'timeStamp': res.data.data.payinfo.timeStamp,
            //   'nonceStr': res.data.data.payinfo.nonceStr,
            //   'package': res.data.data.payinfo.package,
            //   'signType': 'MD5',
            //   'paySign': res.data.data.payinfo.paySign,
            //   'success': function (res) {
            //     console.log("支付结果")
            //     console.log(res)
            //     wx.navigateTo({
            //       url: './Share/share?houBaoStyle=' + that.data.houBaoStyle
            //       + "&Money=" + that.data.Money
            //       + "&Number=" + that.data.Number
            //       + "&kouling=" + that.data.kouling
            //       + "&orderno=" + that.data.orderno,
            //     })
            //   },
            //   'fail': function (res) {
            //     console.log("支付结果")
            //     console.log(res)
            //   }
            // })
          }
        })
      },
    })
   
 
  },
 
  // 获取页面填入的值
  koulingInput:function(e){
    var that = this;
    console.log(e.detail.value)
      that.setData({
        kouling: e.detail.value,
      }) 
  },
  koulingInput1: function (e) {
    var that = this;
    console.log(e.detail.value)
    var conf = app.checkChinese(e.detail.value);
    console.log(conf);
    if (conf) {
      that.setData({
        kouling: e.detail.value,
      })

    } else {
      app.showInfo("请输入中文口令")

    }

  },
  MoneyInput:function(e){
    var that = this;
    console.log(e.detail.value)
    var reg = new RegExp("^\\d+(\\.\\d{0,2})?$");
    if (!reg.test(e.detail.value)) {
      app.showInfo("请您输入正确的金额（只包含两位小数）")
    }else{
      that.setData({
        Money: e.detail.value,
      })
    }
   
  },
  NumberInput: function (e) {
    var that = this;
    console.log(e.detail.value)
    that.setData({
      Number: e.detail.value,
    })
  },
  jubenAnswerInput:function(e){
    var that = this;
    console.log(e.detail.value);
    that.setData({
      answer:e.detail.value,
    })
  },
  // 麦克风帧动画 
  speaking: function () {
    //话筒帧动画 
    var that = this;
    var i = 0;
    that.speakerInterval = setInterval(function () {
      i++;
      i = i % 7;
      that.setData({
        speakerUrl: that.data.speakerUrlPrefix + i + that.data.speakerUrlSuffix,
      });
      console.log("[Console log]:Speaker image changing...");
    }, 300);
  },
  // 页面跳转 
  tojilu:function(){
    var that = this;

  },
  totixian:function(){
    var that = this;
    wx.navigateTo({
      // url: '../tixian/tixian',
      url:'./Share/sharePic'
    })
  },
  tofuli:function(){
    wx.navigateTo({
      url: '../fuli/fuli',
    })
  },
  tomine:function(){
    wx.navigateTo({
      url: '../mine/mine',
    })
  }
})
